#! /usr/bin/env python
# -*- coding: utf-8 -*-
#Author:pako
#Email:zealzpc@gmail.com
"""
some db interface 
"""
import pymongo
import time

connection = pymongo.Connection('localhost', 27017)
db=connection.weibo
pic=db.pic
kw=db.keyword
dy=db.daily

def pic_insert(keyword,url):
    para={
          'keyword':keyword,
          'url':url,
          'lastupdate':time.time()
          }
    pic.insert(para)

def pic_update(keyword,url):
    print "keyword:",keyword,type(keyword)
    print "url:",url,type(url)
    is_exist=pic.find_one({'keyword':keyword})
    if is_exist:
        pic.update({'keyword':keyword},
                   {'$set':{'url':url,'lastupdate':time.time()}},
                   )
    else:
        pic_insert(keyword,url)

def keyword_insert(keyword):
    para={
          'popular':'common',
          'total_count':1,
          'type':'auto',
          'name':keyword
          }
    is_exist=kw.find_one({'name':keyword})
    if is_exist:
        kw.update({'name':keyword},
                   {'$inc':{'total_count':1}},
                   )
    else:
        kw.insert(para)
        
def daily_insert(keyword,count,data,offset,filter=5):
    """
    count:the search result count of keyword
    data:startdata
    offset:interval
    filter:0=all,5=original,4=repost
    """
    para={
          'keyword':keyword,
          'count':count,
          'data':data,
          'offset':offset,
          'filter':filter
          }
    dy.insert(para)
    
def daily_find(keyword,data,offset,filter=5):
    para={
          'keyword':keyword,
          'data':data,
          'offset':offset,
          'filter':filter
          }
    res=dy.find_one(para)
    if res:
        count=res['count']
        return count
    else:
        return None
if __name__ == "__main__":
    connection = pymongo.Connection('localhost', 27017)
    db=connection.weibo
    pic=db.pic
    kw=db.keyword
    dy=db.daily
    
#    pic_update('meihui','c.jpg')
#    keyword_insert('htc')
#    daily_insert('asdf',1000,1304439010,86400)
    print daily_find('iphone4',1305994210,172800,0)
    connection.disconnect()
    